﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using EasyStep.Business.Managers;
using EasyStep.Data.Entities;
using NHibernate.Criterion;
using EasyStep.Business.Interfaces;

namespace EasyStep.Business.Providers
{
    public abstract class DataProviderBase<TEntity>:IDataProvider<TEntity>
        where TEntity : Entity
    {
        protected string connectionString;
        public DataProviderBase(string connectionStringKey = "DefaultConnection")
        {

            connectionString = ConfigurationManager.ConnectionStrings[connectionStringKey].ConnectionString;
        }

        protected virtual SessionManager CreateSessionManager(bool readOnly)
        {
            return new SessionManager(connectionString, readOnly);
        }

        public IList<TEntity> GetAll()
        {
            using (var sm = CreateSessionManager(true))
            {
                return sm.Session.CreateCriteria<TEntity>()
                   .List<TEntity>();
            }
        }


        public TEntity Get(Guid id)
        {
            using (var sm = CreateSessionManager(true))
            {
                return sm.Session.CreateCriteria<TEntity>()
                    .Add(Expression.Eq("Id", id))
                    .UniqueResult<TEntity>();
            }
        }

        public TEntity Create(TEntity data)
        {
            using (var sm = CreateSessionManager(true))
            {
                sm.Session.Save(data);
                sm.Session.Flush();
                return data;
            }
        }
        public TEntity Update(TEntity data)
        {
            using (var sm = CreateSessionManager(true))
            {
                sm.Session.Update(data);
                sm.Session.Flush();
                return data;
            }
        }
        public TEntity Delete(TEntity data)
        {
            using (var sm = CreateSessionManager(true))
            {
                sm.Session.Delete(data);
                sm.Session.Flush();
                return data;
            }
        }
    }
}